package com.cgycms.prototype.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.cgycms.prototype.ProjectManagerService;
import com.cgycms.prototype.UserProjectManagerService;
import com.cgycms.prototype.common.BaseController;
import com.cgycms.prototype.common.Result;
import com.cgycms.prototype.constant.ViewAuthConstant;
import com.cgycms.prototype.model.UserProjectModel;
import com.cgycms.prototype.util.ProjectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @ClassName ViewProjectController
 * @Description 原型功能预览模块
 * @Author 超哥呦
 * @Date 2021/11/29  23:26
 **/
@Api(tags = "原型功能预览模块")
@Controller
@RequestMapping("/view")
public class ViewProjectController extends BaseController {

    @Autowired
    private UserProjectManagerService userProjectManagerService;

    @Autowired
    private ProjectManagerService projectManagerService;

    @ApiOperation(value = "通过项目编码跳转最新的原型地址")
    @GetMapping("/{code}")
    public String viewProjectCode(@PathVariable("code") String code) {
        String uri = projectManagerService.getProjectNewUri(code);
        if (StringUtils.isEmpty(uri)) {
            return "redirect:/404";
        }
        return "redirect:" + uri;
    }

    @ApiOperation(value = "访问项目登录页面")
    @GetMapping("/viewLogin")
    public ModelAndView viewLogin(@RequestParam String uri) {
        ModelAndView modelAndView = new ModelAndView("viewLogin");
        modelAndView.addObject("uri" , uri);
        return modelAndView;
    }

    @ApiOperation(value = "访问项目登录验证")
    @PostMapping("/viewLogin")
    @ResponseBody
    public Result viewLoginPost(@RequestParam Map<String, String> data, HttpServletResponse response) {
        String uri = data.get("uri");
        String password = data.get("password");
        if (ObjectUtil.isEmpty(uri)) {
            return error("参数异常,请重新打开地址！");
        }
        if (ObjectUtil.isEmpty(password)) {
            return error("您还没有输入密码，请先密码哦！");
        }
        UserProjectModel userProjectEntity = userProjectManagerService.getProjectDataByUri(uri);
        if (ObjectUtil.isNull(userProjectEntity)) {
            return error("没有找到项目,请联系作者哦！");
        }
        if (!userProjectEntity.getProjectPassword().toLowerCase().equals(password.trim().toLowerCase())) {
            return error("访问密码错误,请重新输入哦！");
        }
        ServletUtil.addCookie(response, ViewAuthConstant.ACCESS_PASSWORD_KEY + ProjectUtil.getProjectCode(uri), userProjectEntity.getProjectPassword(), -1);
        return success(userProjectEntity.getPreviewUrl());
    }
}
